#include "message_service.h"
#include "stream_reader.h"
#include "c_msg.h"

MessageMgr gMessageMgr;

MessageMgr::~MessageMgr() {
	for (int32 listIndex = 0; listIndex < CACHE_MSG_LIST_NUM; listIndex++) {
		for (int32 i = 0; i < (int32)cacheMsgList_[listIndex].size(); i++) {
			if (cacheMsgList_[listIndex][i].msg_) {
				delete cacheMsgList_[listIndex][i].msg_;
			}
		}
		cacheMsgList_[listIndex].clear();
	}
	
	for (int32 listIndex = 0; listIndex < CACHE_MSG_LIST_NUM; listIndex++) {
		for (int32 i = 0; i < (int32)msgList_[listIndex].size(); i++) {
			if (msgList_[listIndex][i].msg_) {
				delete msgList_[listIndex][i].msg_;
			}
		}
		msgList_[listIndex].clear();
	}
}

void MessageMgr::process() {
	for (int32 listIndex = 0; listIndex < CACHE_MSG_LIST_NUM; listIndex++) {
		std::mutex& curLock = lock_[listIndex];
		CacheMsgList& curCacheMsgList = cacheMsgList_[listIndex];
		CacheMsgList& curMsgList = msgList_[listIndex];
		curLock.lock();
		curMsgList.swap(curCacheMsgList);
		curLock.unlock();
		for (size_t i = 0; i < curMsgList.size(); i++) {
			const CacheMessage& cacheMsg = curMsgList[i];
			MsgQueueMap::iterator itr = queueMap_.find(cacheMsg.handle_);
			if (itr != queueMap_.end()) {
				itr->second->push(cacheMsg.msg_);
			}
			else {
				uint8 msgType;
				std::string msgName;
				StreamReader reader(*cacheMsg.msg_);
				reader >> msgType >> msgName;
				if (msgName == "reqRemoteScriptCall") {
					uint64 retHandle;
					uint64 coid;
					reader >> retHandle >> coid;
					CMessage msg("reqRetCoroutine");
					msg << (uint8)1;
					msg << (uint8)MSGPARAM_TINTEGER;
					msg << coid;
					gMessageMgr.sendMessage(retHandle, msg.msg());
				}
				cacheMsg.msg_->release();
			}
		}
		curMsgList.clear();
	}
}
